/**
 * 在线拍照
 */
package com.stone.paint;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.stone.common.pojo.TFile;
import com.stone.common.service.FileService;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TUser;
import com.stone.utils.DateFormatTool;

import frm.ssh.dao.BaseDAO;

import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author kevin cheng
 *
 */
public class onLineDrawServlet extends HttpServlet {
	private static final long serialVersionUID = 1354876191194195586L;
	
	@Autowired 
	private BaseDAO baseDAO;
	@Autowired 
    public void init(ServletConfig config) throws ServletException {  
    	super.init();
    	ServletContext servletContext = config.getServletContext();
    	super.init();     
         
        WebApplicationContext webApplicationContext = WebApplicationContextUtils  
                .getWebApplicationContext(servletContext);  
        AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext  
                .getAutowireCapableBeanFactory();  
//        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,  
//                config.getServletContext()); 
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(config.getServletContext());
        autowireCapableBeanFactory.configureBean(this, "fileService");  
    }  
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)    
	throws ServletException, IOException {    
	processRequest(request, response);    
	}    
	  
	public void doPost(HttpServletRequest request, HttpServletResponse response)    
	 throws ServletException, IOException {    
	processRequest(request, response);    
	}    
	
	public void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		String kzkid = request.getParameter("kzkid");
		System.out.println("===kzkid=======" + kzkid);
		try {   
			String filePath = request.getRealPath("/") + "upload/security_meature";
			File upDir = new File(filePath);
			if (!upDir.exists()) {
				upDir.mkdirs();
			}

			String saveName = UUID.randomUUID().toString();// maybe change to fixed file name per the requirement
			String fileName = saveName + ".jpg";
	        File f = new File(filePath+"\\" + fileName);
	        if(f.exists())
	        	f.delete();
	        
			BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream());
			FileOutputStream outputStream = new FileOutputStream(f);
            
			//写图片
			byte [] bytes = new byte[1024];

			int v;
			while((v=inputStream.read(bytes))>0){
			outputStream.write(bytes,0,v);
			}
			outputStream.close();
			inputStream.close();
			
			String sql="from TFile where tableid = '" + kzkid + "' AND colname = 'TAB_SECURITY_PIC'";
			TFile tmpFile = (TFile)baseDAO.findFirst(sql);
			if(tmpFile != null){
				File delFile = new File(filePath + "\\" + tmpFile.getRealfilename());
				if(delFile.exists())
					delFile.delete();
				baseDAO.delete(tmpFile.getId(), TFile.class.getName());
			}
			
            String url = "/DLPLANMIS/upload/security_meature/"+fileName;
            Calendar cal = new GregorianCalendar();
    		SimpleDateFormat r = new SimpleDateFormat("yyyy-MM-dd");
			sql = "INSERT INTO tab_file VALUES(seq_file.nextval, "
				+ " '" + fileName + "',"
				+ " '" + fileName + "',"
				+ " '" + url + "',"
				+ kzkid + ","
				+ " 'TAB_SECURITY_PIC',"
				+ " to_date('"+r.format(cal.getTime())+"', 'yyyy-MM-dd'),"
				+ " '" + ((TUser) request.getSession().getAttribute(
						IConstant.SESSION_TUSER)).getId() + "', "
				+ " '1')";
//    		TFile tFile = new TFile();
//    		tFile.setUrl(url);
//    		tFile.setFilename(fileName);
//    		tFile.setRealfilename(fileName);
//    		tFile.setTableid(Long.parseLong(kzkid));
//    		tFile.setColname("TAB_SECURITY_PIC");
//    		tFile.setOperdate(DateFormatTool.formatToDate(r.format(cal.getTime()), false));
//    		tFile.setOperuser(((TUser) request.getSession().getAttribute(IConstant.SESSION_TUSER)).getId());
//    		tFile.setImageflag("1");
//    		baseDAO.save(tFile);
    		baseDAO.insertBySql(sql);
    		
    		
			//baseDAO.updateByHQL("update MainWorkCardOne set pic_id = '"+tFile.getId()+"' where id_sno = ?", new Object[]{Long.parseLong(kzkid)});
        }
        catch(Exception ex)
        {
        	response.setContentType("text/xml");   
            response.getWriter().write("图片保存失败"); 
            ex.printStackTrace();
        }
	}

	/**
	 * @return the baseDAO
	 */
	public BaseDAO getBaseDAO() {
		return baseDAO;
	}

	/**
	 * @param baseDAO the baseDAO to set
	 */
	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}
}
